﻿using Company.IO;
using Company.Share.Prism;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace Company.Config
{
    /// <summary>
    /// 配置服务
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class ConfigService<T> where T : class
    {
        /// <summary>
        /// 从xml文件读取
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        public T GetFromXmlFile(string filePath)
        {
            if (!File.Exists(filePath)) return null;
            using (FileStream stream = new FileStream(filePath, FileMode.Open))
            {
                T xmlConfig = new XmlSerializer(typeof(T)).Deserialize(stream) as T;
                return xmlConfig;
            }
        }
        /// <summary>
        /// 保存到xml文件
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="obj">数据</param>
        public void SaveToXmlFile(string filePath,T obj) 
        {
            if (!File.Exists(filePath))
            { 
                File.Create(filePath).Close();
            }
            using (FileStream stream = new FileStream(filePath, FileMode.Open))
            {
               new XmlSerializer(typeof(T)).Serialize(stream, obj);
            }
        }
    }
}
